'use client'

import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { toast } from 'sonner'
import { updateContract } from '../actions/contract-actions'
import { getContractById } from '../actions/data-actions'
import { ProjectSelector } from './project-selector'
import { VendorSelector } from './vendor-selector'
import { ContractSelector } from './contract-selector'

interface Project {
  id: number
  code: string
  name: string
  type: string
}

interface Vendor {
  id: number
  vendorName: string
  vendorCode: string | null
  status: string
}

interface Contract {
  id: number
  contractNo: string
  contractName: string
  status: string
  projectId: number
  vendorId: number
  projectCode: string | null
  projectName: string | null
  vendorName: string | null
  vendorCode: string | null
}

interface ContractEditFormProps {
  onContractUpdated?: (contract: { id: number; contractNo: string; contractName: string; status: string }) => void
}

export function ContractEditForm({ onContractUpdated }: ContractEditFormProps) {
  const [loading, setLoading] = useState(false)
  const [selectedContract, setSelectedContract] = useState<Contract | undefined>()
  const [selectedProject, setSelectedProject] = useState<Project | undefined>()
  const [selectedVendor, setSelectedVendor] = useState<Vendor | undefined>()
  const [formData, setFormData] = useState({
    contractName: '',
    status: 'TEST'
  })

  // 계약 선택 시 데이터 로드
  useEffect(() => {
    if (selectedContract) {
      loadContractData(selectedContract.id)
    }
  }, [selectedContract])

  const loadContractData = async (contractId: number) => {
    try {
      const result = await getContractById(contractId)
      if (result.success) {
        const contract = result.data
        setFormData({
          contractName: contract.contractName,
          status: contract.status
        })
        
        // 프로젝트 정보 설정
        if (contract.projectId && contract.projectCode) {
          setSelectedProject({
            id: contract.projectId,
            code: contract.projectCode,
            name: contract.projectName || '',
            type: ''
          })
        }
        
        // 벤더 정보 설정
        if (contract.vendorId && contract.vendorName) {
          setSelectedVendor({
            id: contract.vendorId,
            vendorName: contract.vendorName,
            vendorCode: contract.vendorCode,
            status: 'ACTIVE'
          })
        }
      } else {
        toast.error(result.error)
      }
    } catch (error) {
      toast.error('계약 정보를 불러오는 중 오류가 발생했습니다.')
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!selectedContract) {
      toast.error('수정할 계약을 선택해주세요.')
      return
    }
    
    if (!selectedProject || !selectedVendor || !formData.contractName.trim()) {
      toast.error('모든 필수 항목을 입력해주세요.')
      return
    }

    setLoading(true)
    try {
      const result = await updateContract(selectedContract.id, {
        projectId: selectedProject.id,
        vendorId: selectedVendor.id,
        contractName: formData.contractName,
        status: formData.status
      })
      
      if (result.success) {
        toast.success(result.message)
        onContractUpdated?.(result.data)
      } else {
        toast.error(result.error)
      }
    } catch (error) {
      toast.error('계약 수정 중 오류가 발생했습니다.')
    } finally {
      setLoading(false)
    }
  }

  const handleContractSelect = (contract: Contract) => {
    setSelectedContract(contract)
    // 폼 초기화
    setSelectedProject(undefined)
    setSelectedVendor(undefined)
    setFormData({
      contractName: '',
      status: 'TEST'
    })
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>계약 수정</CardTitle>
        <CardDescription>
          기존 계약의 정보를 수정합니다.
        </CardDescription>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <Label>수정할 계약 선택 *</Label>
            <ContractSelector
              selectedContract={selectedContract}
              onContractSelect={handleContractSelect}
              disabled={loading}
            />
          </div>

          {selectedContract && (
            <>
              <div className="bg-muted/50 p-3 rounded-md">
                <div className="text-sm font-medium">선택된 계약</div>
                <div className="text-sm text-muted-foreground">
                  [{selectedContract.contractNo}] {selectedContract.contractName}
                </div>
              </div>

              <div>
                <Label>프로젝트 *</Label>
                <ProjectSelector
                  selectedProject={selectedProject}
                  onProjectSelect={setSelectedProject}
                  disabled={loading}
                />
              </div>

              <div>
                <Label>벤더 *</Label>
                <VendorSelector
                  selectedVendor={selectedVendor}
                  onVendorSelect={setSelectedVendor}
                  disabled={loading}
                />
              </div>

              <div>
                <Label htmlFor="contractName">계약명 *</Label>
                <Input
                  id="contractName"
                  type="text"
                  value={formData.contractName}
                  onChange={(e) => setFormData(prev => ({ ...prev, contractName: e.target.value }))}
                  placeholder="계약명을 입력하세요"
                />
              </div>

              <div>
                <Label htmlFor="status">계약 상태</Label>
                <Select
                  value={formData.status}
                  onValueChange={(value) => setFormData(prev => ({ ...prev, status: value }))}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="TEST">TEST</SelectItem>
                    <SelectItem value="DRAFT">DRAFT</SelectItem>
                    <SelectItem value="ACTIVE">ACTIVE</SelectItem>
                    <SelectItem value="PENDING">PENDING</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <Button type="submit" disabled={loading} className="w-full">
                {loading ? '수정 중...' : '계약 수정'}
              </Button>
            </>
          )}
        </form>
      </CardContent>
    </Card>
  )
}
